package fr.esgi.pages;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fr.esgi.classes.Personne;
import fr.esgi.donnees.Database;

/**
 * Servlet implementation class ValidationConnexion
 */

public class ValidationConnexion extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ValidationConnexion() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String mail=request.getParameter("email");
		String  mdp=request.getParameter("mdp");
		Database db=new Database();
		try {
			if (db.verificationPersonne(mail, mdp)){
				Personne p=db.buildPersonne(mail);
				HttpSession session = request.getSession();
				session.setAttribute("uid", p.getUid());
				session.setAttribute("prenom", p.getPrenom());
				session.setAttribute("nom", p.getNom());
				session.setAttribute("role", p.getRole());
				if(p.getRole().equals("etudiant")||p.getRole().equals("administration")||p.getRole().equals("professeur")){
					getServletContext().getRequestDispatcher("/AccueilConnexion").forward(request, response);
				}
				
				else getServletContext().getRequestDispatcher("/jsp/pages/default.jsp").forward(request, response);
			}
			else {
				request.setAttribute("erreur", "erreur du couple login, mot de passe");
				getServletContext().getRequestDispatcher("/Accueil").forward(request, response);
			}
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
